package com.zhilei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zhilei.base.BaseInfoProperties;
import com.zhilei.exceptions.GraceException;
import com.zhilei.grace.result.ResponseStatusEnum;
import com.zhilei.mapper.AdminMapper;
import com.zhilei.pojo.Admin;
import com.zhilei.pojo.bo.CreateAdminBO;
import com.zhilei.pojo.bo.UpdateAdminBO;
import com.zhilei.pojo.bo.UpdateAdminPwdBO;
import com.zhilei.pojo.vo.AdminVO;
import com.zhilei.service.AdminService;
import com.zhilei.untils.MD5Utils;
import com.zhilei.untils.PagedGridResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 慕聘网运营管理系统的admin账户表，仅登录，不提供注册 服务实现类
 * </p>
 *
 * @author 志磊
 * @since 2024-09-08
 */
@Service
@Slf4j
public class AdminServiceImpl extends BaseInfoProperties implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 创建管理员账号
     *
     * @param createAdminBO
     * @return
     */
    @Transactional
    @Override
    public void createAdmin(CreateAdminBO createAdminBO) {

        String username = createAdminBO.getUsername();

        Admin getAdmin = adminInfo(username);
        // TODO 如果 admin 为空，抛出 GraceException
        if (getAdmin != null) {
            GraceException.disPlay(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }

        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setCreateTime(LocalDateTime.now());
        admin.setUpdatedTime(LocalDateTime.now());
        admin.setRemark(createAdminBO.getRemark());
        admin.setFace("https://img1.pconline.com.cn/piclib/200804/27/batch/1/1729/1209310588678ilj9zu1h9x.jpg");

        // 生成4位随机数字
        String randomNum = String.format("%04d", (int) (Math.random() * 10000));
        log.debug("生成的随机数是：{}", randomNum);
        admin.setSlat(randomNum);

        // 获得传入的密码
        String adminBOPassword = createAdminBO.getPassword();
        // 进行MD5加密
        String pwd = MD5Utils.encrypt(adminBOPassword, randomNum);
        // 存储
        admin.setPassword(pwd);

        adminMapper.insert(admin);
    }

    /**
     * 根据用户名删除管理员
     *
     * @param username
     */
    @Override
    public void deleteAdmin(String username) {
        Admin admin = adminInfo(username);
        if (admin == null) {
            GraceException.disPlay(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }

        if ("admin".equalsIgnoreCase(admin.getUsername())) {
            GraceException.disPlay(ResponseStatusEnum.ADMIN_DELETE_ERROR);
        } else {
            adminMapper.deleteById(admin.getId());
        }
    }

    /**
     * 更新密码
     *
     * @param updateAdminPwdBO
     */
    @Transactional
    @Override
    public void updateAdminPwdBO(UpdateAdminPwdBO updateAdminPwdBO) {

        String adminId = updateAdminPwdBO.getAdminId();
        String password = updateAdminPwdBO.getPassword();
        String rePassword = updateAdminPwdBO.getRePassword();

        if (!password.equalsIgnoreCase(rePassword)) {
            GraceException.disPlay(ResponseStatusEnum.ADMIN_PASSWORD_ERROR);
        }

        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            GraceException.disPlay(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }

        String slat = admin.getSlat();
        String pwd = MD5Utils.encrypt(rePassword, slat);

        admin.setPassword(pwd);

        // 更新用户信息
        adminMapper.updateById(admin);
    }

    /**
     * 根据用户名查询列表数据
     *
     * @param accountName
     * @return
     */
    @Override
    public PagedGridResult getAdminListPaged(String accountName, Integer page, Integer limit) {
        if (page == null) page = 1;

        if (limit == null) limit = 10;

        PageHelper.startPage(page, limit);

        List<Admin> adminList = adminMapper.selectList(new QueryWrapper<Admin>()
                .like("username", accountName)
                .orderByDesc("create_time")
                .orderByDesc("updated_time"));

        ArrayList<AdminVO> adminVOS = new ArrayList<>();

        for (Admin admin : adminList) {
            AdminVO adminVO = new AdminVO();
            BeanUtils.copyProperties(admin, adminVO);
            adminVOS.add(adminVO);
        }

        return setterPagedGrid(adminVOS, page);
    }

    /**
     * 重新查询最新的admin用户信息
     *
     * @param id
     * @return
     */
    @Override
    public Admin getById(String id) {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("id", id));
        return admin;
    }

    /**
     * 更新用户信息到数据库中
     *
     * @param updateAdminBO
     */
    @Override
    public void updateMyInfo(UpdateAdminBO updateAdminBO) {

        Admin admin = adminMapper.selectById(updateAdminBO.getId());
        if (admin == null) {
            GraceException.disPlay(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }

        admin.setUsername(updateAdminBO.getUsername());
        admin.setRemark(updateAdminBO.getRemark());
        admin.setFace(updateAdminBO.getFace());

        adminMapper.updateById(admin);

    }

    /**
     * 封装查询用户的方法
     *
     * @param username
     * @return
     */
    private Admin adminInfo(String username) {

        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }
}
